package forms;

import java.util.ArrayList;
import java.util.Calendar;

import com.devcon5.StudentPlanner.R;

import baseclasses.Assignment;
import baseclasses.Course;
import database.CourseDAO;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import android.widget.ToggleButton;

public class AssignmentForm extends Activity{
	
	protected Context context;
	
	//views, adapters, layouts variables
	protected Spinner courseSpinner;
	protected EditText assignmentName, description;
	protected LinearLayout dueDateLayout, timeDueLayout,reminderLayout;
	protected TextView dueDateText, timeDueText, reminderTextView;
	protected Button addButton, cancelButton;
	protected ArrayAdapter<Course> adapter;
	protected Calendar dueDate;
	protected ToggleButton reminderToggleButton;
	
	
	protected int remindInteger = 24;
	protected String remindString = "hour(s)";
	
	public static final String HOURS = "hour(s)";
	public static final String MINUTES = "minute(s)";
	public static final String DAYS = "day(s)";
	
	// display courses in a Spinner
	protected ArrayList<Course> courses;
	protected ArrayAdapter<Course> spinnerAdapter;
	
	protected String assignmentNameString;
	protected String descriptionString;
	protected int courseID;
	
	//maintains data in case orientation changes
	protected static final String DUE_DATE_LONG = "DUE_DATE_LONG";
	protected static final String REMINDER_INT = "REMINDER_INT";
	protected static final String REMINDER_STRING = "REMINDER_STRING";
	protected static final String TIME_CHANGED = "TIME_CHANGED";
	
	protected long dueDateLong;
	
	//keeps track of time changed
	protected boolean timeChanged;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.addassignment);
		
		this.context = this;
		
		//initialize variables to UI fields
		courseSpinner = (Spinner)findViewById(R.id.addAssignment_CourseSpinner);
		assignmentName = (EditText)findViewById(R.id.addAssignment_AssignmentNameEditText);
		description = (EditText)findViewById(R.id.addAssignment_Description);
		dueDateLayout = (LinearLayout)findViewById(R.id.addAssignment_DueDateLayout);
		dueDateLayout.setBackgroundResource(android.R.drawable.list_selector_background);
		timeDueLayout = (LinearLayout)findViewById(R.id.addassignment_timedue);
		timeDueLayout.setBackgroundResource(android.R.drawable.list_selector_background);
		dueDateText = (TextView)findViewById(R.id.addAssignment_DueDate);
		timeDueText = (TextView)findViewById(R.id.addassignment_time);
		addButton = (Button)findViewById(R.id.addassignment_addbutton);
		cancelButton = (Button)findViewById(R.id.addassignment_cancelbutton);
		reminderLayout = (LinearLayout)findViewById(R.id.addassignment_reminderlayout);
		reminderLayout.setBackgroundResource(android.R.drawable.list_selector_background);
		reminderTextView = (TextView)findViewById(R.id.addassignment_remindertimetextview);
		reminderToggleButton = (ToggleButton)findViewById(R.id.addassignment_remindertogglebutton);
		
		
		
		//get array list of courses from db
		courses = CourseDAO.getCourses(context);
		
		//create new array adapter for the spinner using array list of courses
		spinnerAdapter = new ArrayAdapter<Course>(this,android.R.layout.simple_spinner_item, courses);
		spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		courseSpinner.setAdapter(spinnerAdapter);
		
		//get first course
		courseID = courses.get(0).getId();

		//use a Date Picker Dialog to set the due date on click
		dueDateLayout.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				new DatePickerDialog(context, new OnDateSetListener(){
					public void onDateSet(DatePicker view, int year,
							int monthOfYear, int dayOfMonth) {
						dueDate.set(Calendar.YEAR, year);
						dueDate.set(Calendar.MONTH, monthOfYear);
						dueDate.set(Calendar.DAY_OF_MONTH, dayOfMonth);
						dueDateText.setText(Assignment.getDueDateString(dueDate, "MM/dd/yyyy"));
					}}, dueDate.get(Calendar.YEAR), dueDate.get(Calendar.MONTH),dueDate.get(Calendar.DAY_OF_MONTH)).show();
			}
		});


		
		//use a Time Picker Dialog to set the due time on Click
		timeDueLayout.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				new TimePickerDialog(context, new OnTimeSetListener(){
					public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
						dueDate.set(Calendar.HOUR_OF_DAY, hourOfDay);
						dueDate.set(Calendar.MINUTE, minute);
						timeDueText.setText(Course.getStartTimeString(dueDate, "hh:mm a"));
						timeChanged = true;
					}
				}, dueDate.get(Calendar.HOUR_OF_DAY), dueDate.get(Calendar.MINUTE), false).show();
			}
		});
		
		//Use the Reminder Layout to toggle whether or not to store a reminder
		reminderLayout.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				
				//Instantiate the view objects within the singlealertview layout file
				//will be used in the overall dialog generated when the reminderlayout is clicked
				LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = vi.inflate(R.layout.singlealertview, null);
				
				//Not really a togglebutton--it just has text that changes depending on the user pressing this button
				final Button toggleTime = (Button)v.findViewById(R.id.singlealertview_togglebutton);
				final EditText timeEditText = (EditText)v.findViewById(R.id.singlealertview_numberedittext);
				
				toggleTime.setText(remindString); //hour(s); default remind string
				timeEditText.setText(remindInteger+""); //24; default remind Integer
				
				toggleTime.setOnClickListener(new OnClickListener() { //When the button is pressed and the text is already set to...
			
					public void onClick(View v) {
						
						if(toggleTime.getText().equals(DAYS)){	//...days, change it to hours
							toggleTime.setText(HOURS);
						}
						else if(toggleTime.getText().equals(HOURS)){ //...hours, change it to minutes
							toggleTime.setText(MINUTES);
						}
						else{
							toggleTime.setText(DAYS);	//If it's minutes, change it back to days
						}
					}
				});
				
				//Build the reminder Dialog to set the amount of time to remind before the due time
				//accepts the number input into the numberEditText filed as remindInteger
				//accepts the string created by clicking the toggleTime button as the remind string
				AlertDialog.Builder builder = new AlertDialog.Builder(context);
				builder.setTitle("Remind Me");
				builder.setView(v);
				builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
					
					public void onClick(DialogInterface dialog, int which) {
						try
						{
							remindInteger = Integer.parseInt(timeEditText.getText().toString());
						}
						catch (NumberFormatException e )
						{
							e.printStackTrace();
							return;
						}
						remindString = toggleTime.getText().toString();
						updateReminderTextView();	//Update the reminder text view in the AsssignmentForm to the current integer and units
						reminderToggleButton.setChecked(true);	//If it wasn't already toggled to on, then toggle it since they've set a reminder
					}
				});
				builder.setNegativeButton("Cancel", null);
				AlertDialog alert = builder.create();
				alert.show();	

			}
		});
		
		
		
		
		//When add/save button is clicked on form, verify that there is data
		addButton.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				
				assignmentNameString = assignmentName.getText().toString();
				
				if(assignmentNameString!=null&&assignmentNameString.trim().length()>0){
					
					descriptionString = description.getText().toString();
					onSaveButtonClicked();	//Saves information when save button is clicked
											//Implemented in Add/Edit Assignment classes
					onBackPressed();	//Finishes activity even if back button is pressed
					finish();
					
				}
				else{
					Toast.makeText(context, "Assignment title cannot be blank!", Toast.LENGTH_SHORT).show();
				}
				
			}
		});
		
		
		//If cancel is pressed, finalize and finish
		cancelButton.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				onBackPressed();
				finish();
			}
		});
		
	}
	
	
	//Method is overridden in AddAssignment & EditAssignment classes
	protected void onSaveButtonClicked(){

	}
	
	
	
	//Updates the reminder text view in the AsssignmentForm to the current integer and units
	protected void updateReminderTextView(){
		reminderTextView.setText(remindInteger+" "+remindString+" before");
	}
	
	
	//Validates that the name of the assignment Name exists
	protected boolean validation(String assignmentNameString){
		if(assignmentNameString!=null && assignmentNameString.trim().length()>0){
			return true;
		}
		return false;
	}
}
